import React, { useLayoutEffect, useState } from 'react';
import { Button, Form, Input, message } from 'antd';
import { useNavigate } from "react-router-dom";
import {useSelector, useDispatch } from "react-redux";
import JSEncrypt from 'jsencrypt';
import { login, getPublicKey } from "../../api/login";
import type { RootState } from "../../store";
import { setToken ,setPublicKey} from "../../store/modules/userInfo";
import type { FormProps } from 'antd';
import type { loginReqType } from './../../types/loginType';
import styles from './index.module.scss';


const Login: React.FC = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const publicKey = useSelector((state: RootState) => state.userInfo.publicKey);
  useLayoutEffect(() => {
    getPublicKey().then(res => {
      if (res.code === 0) {
        dispatch(setPublicKey(res.data));
      }
    })
  }, [])

  const onFinish: FormProps<loginReqType>['onFinish'] = (e) => {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey);
    const password = encryptor.encrypt(e.password);

    const obj: loginReqType = {
      ...e,
      password: password || ""
    }
    login(obj).then(res => {
      if (res.code === 0) {
        dispatch(setToken(res.data.token));
        navigate('/');
      } else {
        message.error(res.msg);
      }
    })
  };

  return (
    <div className={styles.Login}>
      <div className={styles.LoginCenter}>
        <h1>游盟社管理后台登录</h1>
        <Form
          style={{ width: 500 }}
          onFinish={onFinish}
          autoComplete="off"
          size="middle"
          layout="vertical"
          initialValues={{
            account: 'shizai',
            password: 'admin123456',
            dynamicCode: '111111'
          }}
        >
          <Form.Item<loginReqType>
            label="账号"
            name="account"
            rules={[{ required: true, message: '账号是必填的!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<loginReqType>
            label="密码"
            name="password"
            rules={[{ required: true, message: '密码是必填的' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item<loginReqType>
            label="验证码"
            name="dynamicCode"
            rules={[{ required: true, message: '验证码是必填的' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 2, span: 20 }}>
            <Button type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Login;
